enum TimeUnit {
    //% block="秒"
    SECOND,
    //% block="毫秒"
    MILLISECOND,
    //% block="微秒"
    MICROSECOND,
}

//% color="#5DE2E7" iconWidth=30 iconHeight=30
namespace milliSmicroS {
    //% block="延时 [DELAY] [UNIT]"
    //% blockType="command"
    //% DELAY.shadow="range" DELAY.params.min=0 DELAY.params.max=10000 DELAY.defl=10
    //% UNIT.shadow="dropdown" UNIT.options="TimeUnit" UNIT.defl="MILLISECOND"
    export function delayCommand(parameter: any, block: any) {
        let delay = parameter.DELAY.code;
        let unitStr = parameter.UNIT.code;

        // 确保 unitStr 是有效的字符串
        let unit: TimeUnit | undefined;
        if (unitStr === "MILLISECOND") {
            unit = TimeUnit.MILLISECOND;
        } else if (unitStr === "MICROSECOND") {
            unit = TimeUnit.MICROSECOND;
        } else if (unitStr === "SECOND") {
            unit = TimeUnit.SECOND;
        } else {
            console.error(`Invalid unit: ${unitStr}`);
            return;
        }

        // 根据选择的单位生成相应的延迟代码
        let delayCode: string;
        if (unit === TimeUnit.MILLISECOND) {
            delayCode = `delay(${delay});`;
        } else if (unit === TimeUnit.MICROSECOND) {
            delayCode = `delayMicroseconds(${delay});`;
        } else if (unit === TimeUnit.SECOND) {
            delayCode = `delay(${delay} * 1000);`;    
        } else {
            console.error(`Invalid unit: ${unitStr}`);
            return;
        }

        // 生成延迟代码
        Generator.addCode(delayCode);
    }

    //% block="系统运行时间 [UNIT]"
    //% blockType="reporter"
    //% UNIT.shadow="dropdown" UNIT.options="TimeUnit" UNIT.defl="MILLISECOND"
    export function sysRuntime(parameter: any, block: any) {
        let unitStr = parameter.UNIT.code;

        // 确保 unitStr 是有效的字符串
        let unit: TimeUnit | undefined;
        if (unitStr === "MILLISECOND") {
            unit = TimeUnit.MILLISECOND;
        } else if (unitStr === "MICROSECOND") {
            unit = TimeUnit.MICROSECOND;
        } else if (unitStr === "SECOND") {
            unit = TimeUnit.SECOND;
        } else {
            console.error(`Invalid unit: ${unitStr}`);
            return;
        }

        // 根据选择的单位生成相应的运行时间代码
        let runTimecode: string;
        if (unit === TimeUnit.MILLISECOND) {
            runTimecode = `millis()`;
        } else if (unit === TimeUnit.MICROSECOND) {
            runTimecode = `micros()`;
        } else if (unit === TimeUnit.SECOND) {
            runTimecode = `millis() / 1000`; // 获取秒
        } else {
            console.error(`Invalid unit: ${unitStr}`);
            return;
        }

        // 生成运行时间代码
        Generator.addCode(runTimecode); // 确保没有多余的分号
    }

    // 添加包含指令
    Generator.addInclude('Arduino', '#include <Arduino.h>');
}

